package com.xiyou.week02.map;

import java.util.HashMap;
import java.util.Map;

/**
 * 146. LRU 缓存
 *
 * @ClassName：LRUCache
 * @Author：西柚
 * @Date：2022/1/11 12:00 上午
 * @Versiion：1.0
 */
public class LRUCache {

    private class Node {
        int key;
        int value;
        Node pre;
        Node next;
    }

    private Map<Integer, Node> h = new HashMap<>();
    private Node head;
    private Node tail;
    private Integer capacity;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        head = new Node();
        tail = new Node();
        head.next = tail;
        tail.pre = head;
    }

    public int get(int key) {
        if (!h.containsKey(key)) {
            return -1;
        }
        Node node = h.get(key);
        remove(node);
        insert(head, node);
        return node.value;
    }

    public void put(int key, int value) {
        if (!h.containsKey(key)) {
            Node node = new Node();
            node.key = key;
            node.value = value;
            h.put(key, node);
            insert(head, node);
            if (h.size() > capacity) {
                h.remove(tail.pre.key);
                remove(tail.pre);
            }
        } else {
            Node node = h.get(key);
            node.value = value;
            remove(node);
            insert(head, node);
        }
    }

    private void remove(Node node) {
        node.pre.next = node.next;
        node.next.pre = node.pre;
    }

    private void insert(Node p, Node node) {
        p.next.pre = node;
        node.next = p.next;
        p.next = node;
        node.pre = p;
    }
}
